package com.webrtc.demo.contacts.adapter

import android.widget.Toast
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.webrtc.demo.R
import com.webrtc.demo.model.Contacts
import kotlinx.android.synthetic.main.item_contacts_select_list.view.*

class ContactsSelectListAdapter :
    BaseQuickAdapter<Contacts, BaseViewHolder>(R.layout.item_contacts_select_list) {

    private val selectedUids = mutableSetOf<String>()

    fun getSelectedUidList() = selectedUids.toList()

    init {
        setOnItemClickListener { adapter, view, position ->
            view.checkbox.isChecked = !view.checkbox.isChecked
        }
    }

    override fun convert(helper: BaseViewHolder, item: Contacts) {
        helper.itemView.run {
            val name = if (!item.nickname.isNullOrEmpty()) {
                "(" + item.nickname + ")" + item.uid
            } else {
                item.uid
            }
            nameTv.text = name
            checkbox.isChecked = selectedUids.contains(item.uid)
            checkbox.setOnCheckedChangeListener { buttonView, isChecked ->
                if (isChecked) {
                    if (selectedUids.size >= 8) {
                        Toast.makeText(context, "最多不能超过8人", Toast.LENGTH_SHORT).show()
                        buttonView.isChecked = false
                    } else {
                        selectedUids.add(item.uid)
                    }
                } else {
                    selectedUids.remove(item.uid)
                }
            }
        }
    }

}